define(["mock", "allTpl", "rangeslider"], function (Mock, template, rangeslider) {
    var popWrap = new popF();
    return {
        init: function () {
            var ShoppingCart = this;

            /***
             * 模拟数据
             */
                //购物车
        /*    Mock.mock(__base.url.shoppingCar.GetShoppingCartList, {
                "Code": "0",
                "Message": null,
                "Data": [{
                    "MaxPoints": 10000,
                    "MaxPrice": 1300.00,
                    "ProductAttribute": "红色",
                    "ShopCartSysNo": 31,
                    "ProductSysNo": 5,
                    "StockSysNo": 1,
                    "C3SysNo": 5,
                    "ProductName": "==BOSMA博冠望远镜专柜同步双筒保罗7X50高清高倍微光夜视户外323020",
                    "ProductPic": "http://img11.360buyimg.com/n1/g15/M00/19/0F/rBEhWlNbKFYIAAAAAAPzuYMTUgMAAMbigPZIcUAA_PR925.jpg",
                    "Score": 1000,
                    "Price": 150.00,
                    "ProductQuantity": 1
                }
                , {
                    "MaxPoints": 10000,
                    "MaxPrice": 2600.00,
                    "ProductAttribute": "红色",
                    "ShopCartSysNo": 30,
                    "ProductSysNo": 1,
                    "StockSysNo": 1,
                    "C3SysNo": 4,
                    "ProductName": "魅族 魅蓝2 16GB 双卡双待手机 白色 移动4G 标配版123",
                    "ProductPic": "http://img11.360buyimg.com/n0/jfs/t1432/179/83863703/321191/14cdaabe/5556f094N3f714fc0.jpg",
                    "Score": 5000,
                    "Price": 1200.00,
                    "ProductQuantity": 2
                }
                , {
                    "MaxPoints": 10000,
                    "MaxPrice": 2345.00,
                    "ProductAttribute": "IE80",
                    "ShopCartSysNo": 29,
                    "ProductSysNo": 15,
                    "StockSysNo": 1,
                    "C3SysNo": 11,
                    "ProductName": "森海塞尔（Sennheiser） IE80 入耳式HiFi耳机 经典旗舰 黑色",
                    "ProductPic": "http://img14.360buyimg.com/n1/jfs/t742/265/11940749/74696/1e0a8128/547d2cadN32b2cd21.jpg",
                    "Score": 3000,
                    "Price": 3300.00,
                    "ProductQuantity": 1
                }
                ]
            });*/

            // 修改购物车
      /*      Mock.mock(_CONFIG[__webState]["AJAX_URL"] + "/api/ShoppingCart/UpdateShoppingCart", {
                "Code": "0",
                "Data": "ok",
                "Message": "3333"
            });
*/
            // 请求购物车列表
            new __base.AjaxFun({
                "url": __base.url.shoppingCar.GetShoppingCartList,
                "data": {}
            }, function (data) {
            	ajaxLoading.remove();
            	var $shoppingCarPage = $("#shoppingCarPage");
                if (data["Code"] === "0") {

                    if (data["Data"] === null) {
                        $shoppingCarPage.html(_CONFIG[__webState].noCartData.addClass("absolute"));
                        return false;
                    }

                    var html = template("Reservation/shoppingCarPage/shoppingCarPage", data["Data"])
                        .replace(/%URL%/g, _CONFIG[__webState].goodsPage_URL);

                    ShoppingCart.WrapObj = $('#shoppingCarPage');
                    ShoppingCart.WrapObj.append(html);
                    ShoppingCart.ItemObj = $(".item_shoppingCarPage");
                    ShoppingCart.FooterBox = ShoppingCart.WrapObj.find(".footerBox_Global");
                    ShoppingCart.IconAll = ShoppingCart.FooterBox.find('.icon-all');

                    ShoppingCart.itemCount(data);

                } else {
                    popWrap.alert({autoClose:false,content:data['Message']});
                }

            });


        },
        itemCount: function (data) {

            console.log(data["Data"]);
            var ShoppingCart = this,
                goToOrder = function () {
                    var countGoods = 0;
                    ShoppingCart.ItemObj.each(function () {
                        if ($(this).hasClass("current")){
                            countGoods += Number($(this).find(".value_cfo").val());
                        }
                    });
                    ShoppingCart.FooterBox.find(".rd").html("去结算("+ countGoods + ")");
                };
            ShoppingCart.ItemObj.each(function () {
                var _thisItem = $(this);
                var $value_cfo = _thisItem.find('.value_cfo'),
                    $remove_cfo = _thisItem.find('.remove_cfo'),
                    $add_cfo = _thisItem.find('.add_cfo'),
                    MaxPoints = _thisItem.attr('data-MaxPoints'),
                    MaxPrice = _thisItem.attr('data-MaxPrice'),
                    DataPrice = _thisItem.attr('data-Price'),
                    DataPoints = _thisItem.attr('data-Score'),
                    Rate = 0.025,
                    PointsIncrement = 1,
                    //PriceIncrement = 2.5,
                    $price_count = _thisItem.find('.price_count'),
                    $point_count = _thisItem.find('.point_count'),
                    shopcartsysno = _thisItem.attr('data-shopcartsysno'),
                    $range = _thisItem.find('input[type="range"]'),
                //取得当前商品数量
                    getCount = function () {
                        return Number($value_cfo.val());
                    },
                //取得当前商品价格
                    getPriceCount = function () {
                        return Number($price_count.text());
                    },
                //取得当前商品积分
                    getPointCount = function () {
                        return Number($point_count.text());
                    },
                    Points = Number(DataPoints),
                    Price = Number(DataPrice),
                // 积分和金额兑换比例
                    rangeInit = function () {

                        countPoints();

                        // 假如现金不足全部兑换积分，则设置$range为当前现金能够兑换的最大积分
                        var dis_price = DataPrice  / Rate + Number(DataPoints);
                        //console.log( dis_price );

                        // 假如现金足够全部兑换积分，则设置$range为最大积分
                        if ( dis_price > MaxPoints ){
                            dis_price = MaxPoints
                        }

                        $range.attr({
                            "max": dis_price,
                            "step": PointsIncrement
                        });
                        $range.val( DataPoints );

                        $range.rangeslider({
                            polyfill: false,
                            onSlide: function (position, value) {
                                var NowPriceTotal = 0;

                                if (value > Points) {
                                    NowPriceTotal = Number(Price) - Number(value - Points) * Rate;
                                } else {
                                    NowPriceTotal = Number(Price) + Number(Points - value) * Rate;
                                }

                                //console.log("当前积分：" + value, "当前金额：" + NowPriceTotal);
                                $price_count.text(NowPriceTotal.toFixed(2));
                                $point_count.text(Number(value));
                            },
                            onSlideEnd: function (position, value) {

                                //Price = Number($price_count.text());
                                //Points = Number(value);

                                ShoppingCart.countTotal();

                            }
                        });
                    },
                //计算 数量和 金额 积分
                    countPoints = function () {
                        $price_count.html(Price.toFixed(2));
                        $point_count.html(Points);
                        //console.log("------>",Price,Points);
                        //console.log( "金额："+ Price * Count , "积分："+ Points * Count );
                    },
                // 修改购物车
                    UpdateShoppingCart = function (sysNo, count, callback) {
                        new __base.AjaxFun({
                            "url": _CONFIG[__webState]["AJAX_URL"] + "api/ShoppingCart/UpdateShoppingCart",
                            "data": {
                                sysNo: sysNo, //系统编码
                                number: count, //商品数量
                                CurrentPrice: DataPrice , //如果页面上输入了 当前价格则传页面值 否则传商品价格的CurrentPrice
                                CurrentScore: DataPoints  //如果页面上输入了 当前积分则传页面值 否则传商品积分的CurrentScore
                            }
                        }, function (data) {
                            if (data["Code"] === "0") {
                        		popWrap.alertRemove().alert({content:"修改成功",autoClose:300});
                                callback();
                                //$range.rangeslider('destroy');
                                //rangeInit();
                                countPoints();
                                goToOrder();
                                ShoppingCart.countTotal();
                            } else {
                                popWrap.alertRemove().alert({content:data['Message'],autoClose:300});
                            }
                        });
                    };




                //console.log(MaxPoints, MaxPrice, Points, Price);

                //调整兑换
                rangeInit();
                //计算 数量和金额积分
                countPoints();



                // 商品数量
                $remove_cfo.click(function () {
                    if (getCount() <= 1) {
                        return false
                    }
                    popWrap.alert({content:"正在修改，请稍后",autoClose:false});
                    UpdateShoppingCart(shopcartsysno, getCount() - 1, function () {
                        $value_cfo.val(getCount() - 1);

                    });
                });
                $add_cfo.click(function () {
                    popWrap.alert({content:"正在修改，请稍后",autoClose:false});
                    UpdateShoppingCart(shopcartsysno, getCount() + 1, function () {
                        $value_cfo.val(getCount() + 1);
                    });
                });




                // 删除购物车 start
                _thisItem.find(".icon-del").on('click', function () {
                    popWrap.defult({
                        content: "是否确定删除该订单",
                        btnNum: 2,
                        btn_r: "知道了",
                        confirm:function(){
                        	popWrap.alert({content:"正在删除，请稍后",autoClose:false});
                        	new __base.AjaxFun({
			                      "url": __base.url.shoppingCar.DeleteShoppingCart,
			                      "data": {
			                          sysNo: _thisItem.attr("data-ShopCartSysNo") //系统编码
			                      }
			                  }, function (data_DeleteShoppingCart) {
			                      if (data_DeleteShoppingCart["Code"] === "0") {
										popWrap.alertRemove().alert({content:"删除成功"});
			                           _thisItem.slideUp(400,function(){
			                           		_thisItem.remove();
			                           		if($("#shoppingCarPage .item_shoppingCarPage").length == 0){
			                           			$("#shoppingCarPage").html(_CONFIG[__webState].noCartData.addClass("absolute"));
			                           		};
			                           });
			                      } else {
			                          popWrap.defult({  
			                              content: data_DeleteShoppingCart['Message'],
			                              btnNum: 1,
			                              btn_r: "知道了"
			                          });
			                          popWrap.alertRemove().alert({content:data_DeleteShoppingCart['Message']});
			                      }
			                  });
                        }
                    });
                });
                // 删除购物车 end

                // 是否选择购物车
                _thisItem.find(".icon-bg").on('click', function () {
                    if (_thisItem.hasClass("current")) {
                        _thisItem.removeClass("current");
                    } else {
                        _thisItem.addClass("current");
                    }
                    checkAll(function () {
                        ShoppingCart.IconAll.removeClass("current");
                    }, function () {
                        ShoppingCart.IconAll.addClass("current");
                    });
                    goToOrder();
                });

                //var PointsTotal = Points * $value_cfo.val(), // 积分乘以数量
                //    MaxPointsTotal = MaxPoints * $value_cfo.val(), // 最大积分乘以数量
                //    MaxPriceTotal = Price * $value_cfo.val();

            }); // ShoppingCart.ItemObj.each END

            // 去结算
            goToOrder();

            ShoppingCart.countTotal();


            // 底部条


            // 全选按钮以及价格计算
            var checkAll = function (callback1, callback2) {
                var num_shoppingCarpage = ShoppingCart.WrapObj.find(".item_shoppingCarPage.current").length;
                if (num_shoppingCarpage < ShoppingCart.ItemObj.length) {
                    callback1();
                } else {
                    callback2();
                }
                goToOrder();
                ShoppingCart.countTotal();
            };

            // 全选
            ShoppingCart.IconAll.addClass("current");
            ShoppingCart.FooterBox.on('click', '.ld', function () {
                checkAll(function () {
                    ShoppingCart.IconAll.addClass("current");
                    ShoppingCart.ItemObj.each(function () {
                        $(this).addClass("current");
                    })
                }, function () {
                    ShoppingCart.IconAll.removeClass("current");
                    ShoppingCart.ItemObj.each(function () {
                        $(this).removeClass("current");
                    })
                });
            });
            ShoppingCart.FooterBox.on('click', '.rd', function () {
                var BatchUpdate = []; //去结算发送json参数字符串

                ShoppingCart.ItemObj.each(function () {
                    BatchUpdate.push({
                        "ShopSysNo": $(this).attr('data-shopcartsysno'),
                        "CurrentPrice":  $(this).attr('data-Price'),
                        "CurrentPoints": $(this).attr('data-Score')
                    });
                });

                __base.AjaxFun({
                    url:__base.url.shoppingCar.BatchUpdate,
                    "data": {
                        jsonstr: JSON.stringify(BatchUpdate)
                    }
                }, function (data) {
                    console.log(data);
                    if (data["Code"] === "0") {
						window.location.href =  _CONFIG[__webState].fillOrderPage_URL;
                    } else {
                        popWrap.defult({
                            content: data['Message'],
                            btnNum: 1,
                            btn_r: "知道了"
                        });
                    }
                });



            });


        },
        //总格价格计算
        countTotal: function () {
            var ShoppingCart = this,
                priceTotal = 0,
                pointTotal = 0,
                $val_c = ShoppingCart.FooterBox.find('.md>p');

            ShoppingCart.ItemObj.each(function () {
                if ($(this).hasClass("current")) {
                    var count = Number($(this).find(".value_cfo").val());
                    priceTotal += Number($(this).find(".price_count").text()) * count;
                    pointTotal += Number($(this).find(".point_count").text()) * count;
                }
            });

            $val_c.eq(0).html('<i>积分&nbsp;&nbsp;&nbsp;</i>' + pointTotal );
            $val_c.eq(1).html('<i>金额￥</i>' + priceTotal.toFixed(2) );
        }

    }
});